package utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

public class IOToolKit {

	public final static String iPSTFormat = ".ipst";
	public final static String tempFilesFormat = ".temp";
	public final static String resultFilesFormat = ".results";
	public final static String feedbackFilesFormat = ".txt"; 
	protected static String FEEDBACK_FILES_DIR = Configuration.getInstance().getProperty(Configuration.FEEDBACK_FILES_DIR);

	public static void saveObject(Object pstModel, String destinationDir,
			String fileName, String format) {

		FileOutputStream fileOut;
		try {
			fileOut = new FileOutputStream(destinationDir + fileName + format);
			ObjectOutputStream salida = new ObjectOutputStream(fileOut);
			salida.writeObject(pstModel);
			salida.close();
			System.out.println("File created: " + destinationDir
					+ fileName + format);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static Object loadObject(String modelsDir, String modelName,
			String format) {
		Object loadedObject = null;
		File pstFile = new File(modelsDir + modelName + format);

		try {
			FileInputStream fip = new FileInputStream(pstFile);
			ObjectInputStream entrada = new ObjectInputStream(fip);
			loadedObject = entrada.readObject();
			// pst.restartSimulation();
			System.out.println("Model loaded: " + modelsDir + modelName
					+ format);
			entrada.close();
			fip.close();
		} catch (FileNotFoundException e) {
			System.out.println("File does not exists");
			return null;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		return loadedObject;
	}
	
	/**
	 * Guarda la cadena chain como feedback para el patron correspondiente
	 * @param feedback_file_path
	 * @param chain
	 */
	public static void saveFeedbackChain(String feedback_file_path, String chain) {
			
			FileWriter fichero = null;
	        PrintWriter pw = null;
	        File txtFile = new File(System.getProperty("user.dir") + feedback_file_path);
	        try
	        {
	            fichero = new FileWriter(txtFile, true);
	            pw = new PrintWriter(fichero);
	            pw.println(chain);
	
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	           try {
		           if (null != fichero)
		              fichero.close();
		           } catch (Exception e2) {
		              e2.printStackTrace();
	           }
	        }
			
	}

}
